<template>
  <div class="contact-list">
    <div class="contact-editor">
      <p>通讯录</p>
      <el-button type="primary" @click="dialogVisible = true , isStatus= 'add'" >新增联系人</el-button>
      <el-button type="primary" @click="dialogVisible2 = true , isStatus= 'addGroup'">管理群组</el-button>
      <el-button type="primary" @click="deleteContact">删除</el-button>
      <el-dialog title="新增/编辑联系人" :visible.sync="dialogVisible">
        <el-card>
        <el-form :model="contactForm" :rules="rules" ref="contactForm" label-width="200px">
          <el-form-item label="联系人姓名" prop="contactName">
            <el-input v-model="contactForm.contactName"  placeholder="请输入联系人姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系人备注" prop="remark" >
            <el-input v-model="contactForm.remark" placeholder="请输入联系人备注"></el-input>
          </el-form-item>
          <el-form-item label="联系人邮箱" prop="email">
            <el-input v-model="contactForm.email" placeholder="请输入联系人邮箱"></el-input>
          </el-form-item>
          <el-form-item label="联系人分组" prop="groupId">
            <el-select v-model="contactForm.groupId"  placeholder="请选择">
              <el-option
                  v-for="item in groups"
                  :key="item.groupId"
                  :label="item.groupName"
                  :value="item.groupId">
              </el-option>
            </el-select>
          </el-form-item>
            <el-button type="primary" @click="addContact" v-if="isStatus==='add'" >添加</el-button>
            <el-button type="primary" @click="updateContact" v-if="isStatus==='update'">更新</el-button>
            <el-button type="primary" @click="dialogVisible = false">取消</el-button>
        </el-form>
        </el-card>
      </el-dialog>
      <el-dialog title="新增/编辑分组" :visible.sync="dialogVisible2">
        <el-card>
          <el-form :model="groupForm" ref="groupForm" label-width="200px">
            <el-form-item label="分组组名" prop="groupName">
              <el-input v-model="groupForm.groupName" placeholder="请输入分组组名"></el-input>
            </el-form-item>
            <el-form-item label="选择操作组名" prop="groupId">
              <el-select v-model="groupForm.groupId" placeholder="请选择">
                <el-option
                    v-for="item in groups"
                    :key="item.groupId"
                    :label="item.groupName"
                    :value="item.groupId">
                </el-option>
              </el-select>
            </el-form-item>

            <el-button type="primary" @click="addGroupContact" v-if="isStatus==='addGroup'&&this.groupForm.groupId===0" >添加</el-button>
            <el-button type="primary" @click="updateGroupContact" v-if="isStatus==='addGroup'&&this.groupForm.groupId!==0">更新</el-button>
            <el-button type="primary" @click="deleteGroupContact" v-if="isStatus==='addGroup'&&this.groupForm.groupId!==0">删除</el-button>
            <el-button type="primary" @click="dialogVisible2 = false">取消</el-button>
          </el-form>
        </el-card>
      </el-dialog>

      <el-table
          ref="multipleTable"
          :data="filteredContacts"
          :cell-style="{'text-align':'center'}"
          :header-cell-style="{'text-align':'center'}"
          tooltip-effect="dark"
          v-model="multipleSelection"
          @selection-change="handleSelectionChange"
          style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="联系人姓名" prop="contactName" ></el-table-column>
        <el-table-column label="联系人备注" prop="remark" ></el-table-column>
        <el-table-column label="联系人邮箱" prop="email"></el-table-column>
        <el-table-column label="联系人分组" prop="groupName" ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.$index, scope.row)" type="primary" size="small">编辑</el-button>
            <el-button @click="handleDelete(scope.$index, scope.row)" type="danger" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="contact-list-content">
      <el-input placeholder="搜索联系人" v-model="searchQuery" @input="handleSearch"></el-input>
      <el-table :data="groups"
                style="width: 100%" class="hide-header-table"
                @row-click="handleGroupClick"
      >

        <el-table-column prop="groupName" label="分组名称" ></el-table-column>

      </el-table>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import validator from "validator";
import {map} from "core-js/internals/array-iteration";
import {mapState} from "vuex";

export default {
  name: 'ContactList',
  inject:['reload'],
  data() {
    const validateEmail=(rule, value, callback)=> {
      const emails = value.split(';');
      const trimmedEmails = emails.map(email => email.trim());
      const uniqueEmails = [...new Set(trimmedEmails)]; // 去除重复项
      // 检查是否有重复的邮箱地址
      if (trimmedEmails.length !== uniqueEmails.length) {
        callback(new Error('邮箱地址中存在重复'));
        return;
      }

      for (const email of emails) {
        if (email.trim() === '') {
          callback();
          return;
        }
        if (!validator.isEmail(email.trim())) {
          callback(new Error('邮箱地址格式不正确'));
        }
      }
      callback();
    };
    return {
      groups: [], // 存储分组信息的数组
      activeNames: [],
      multipleSelection: [],
      contactForm: {
        contactId:'',
        contactName: '',
        email: '',
        remark:'',
        userId:'',
        groupId: 0,

      },
      groupForm:{
        groupId:0,
        groupName:'',
      },
      contactId:'',
      searchQuery:'',
      dialogVisible: false,
      dialogVisible2: false,
      isStatus:'',

      // selectedContacts: [], // 存储当前选中的分组下的联系人列表
      // groupId:1,
      contacts:[],
      rules:{
        contactName:[
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: validateEmail, trigger: ['blur', 'change'] },
          // 可以添加其他规则，例如非空验证等
        ]

      }

    };
  },
  created() {
    this.fetchData();
    this.fetchContactsData();
  },
  computed: {
    ...mapState(['user']),
    filteredContacts() {
      if (!this.searchQuery) {
        return this.contacts;
      }else{
        return this.contacts.filter(contact => {
          return contact.contactName.toLowerCase().includes(this.searchQuery.toLowerCase());
        });
      }
    },
  },
  methods: {
    async fetchData() {
      try {
        // 获取分组列表
        console.log(this.user);
        const groupResponse = await axios.get('http://localhost:8989/contact/group?userId='+this.user.userId);
        console.log(groupResponse.data);
        this.groups = groupResponse.data.map(group => ({
          ...group,
          contacts: [], // 初始化每个分组的联系人列表
        }));

        // 遍历分组列表，获取每个分组的联系人
        for (const group of this.groups) {
          const contactResponse = await axios.get('http://localhost:8989/contact/group_list?groupId='+group.groupId);
          group.contacts = contactResponse.data;
          console.log("分组内容"+group.contacts);
        }

        console.log(this.groups);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
    async fetchContactsData() {
      try {
        const contactResponse = await axios.get('http://localhost:8989/contact/all_list?userId='+this.user.userId);
        this.contacts=contactResponse.data.map(contact => ({
          ...contact,
          groupName: '',
          groupId: '',
        }));
        for (const contact of this.contacts) {
          const groupResponse = await axios.get('http://localhost:8989/contact/group_name?contactId='+contact.contactId);
          contact.groupName = groupResponse.data.groupName;
          contact.groupId = groupResponse.data.groupId;
          console.log(groupResponse.data)
          console.log("联系人分组"+contact.groupName);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
    async handleGroupClick(row) {
      const groupId = row.groupId;
      console.log(groupId);
      if(groupId===0){
        await this.fetchContactsData();
      }else {
        const contactResponse = await axios.get('http://localhost:8989/contact/group_list?groupId='+groupId);
        this.contacts=contactResponse.data.map(contact => ({
          ...contact,
          groupName: '',
        }));
        for (const contact of this.contacts) {
          const groupResponse = await axios.get('http://localhost:8989/contact/group_name?contactId='+contact.contactId);
          contact.groupName = groupResponse.data.groupName;
          console.log(groupResponse.data)
          console.log("联系人分组"+contact.groupName);
        }

      }



    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleHeaderClick(groupId) {
      const index = this.activeNames.indexOf(groupId);
      if (index === -1) {
        this.activeNames.push(groupId);
      } else {
        this.activeNames.splice(index, 1);
      }
    },

    addContact() {
      this.dialogVisible = true;
      console.log("添加表单数据"+this.contactForm.contactName)
      console.log("添加表单数据"+this.contactForm.groupId)
      console.log("添加表单数据"+this.contactForm.email)
      this.contactForm.userId=this.user.userId;
      axios.post('http://localhost:8989/contact/add?groupId='+this.contactForm.groupId, this.contactForm)
        .then((response) => {
          this.reload();
          this.dialogVisible=false;
        });
    },
    updateContact(){
      console.log(this.contactForm)
      axios.post('http://localhost:8989/contact/update?groupId='+this.contactForm.groupId, this.contactForm)
        .then((response) => {
          console.log(response.data)
          this.reload();
          this.dialogVisible = false;
        });
    },
    deleteContact(){
      //复选框删除
        this.$confirm('此操作将删除选中联系人, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const contactIds = this.multipleSelection.map(row => row.contactId);
          for (let i = 0; i < contactIds.length; i++) {
            const contactid = contactIds[i];
            console.log(contactid)
            axios.get('http://localhost:8989/contact/logic_delete?contactId='+contactid)
                .then((response) => {
                  console.log(response.data)
                  this.reload();
                })
          }
          this.multipleSelection = [];
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

    },
    handleDelete(index, row) {
      console.log(row.contactId)
        this.$confirm('此操作将删除该联系人, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.get('http://localhost:8989/contact/logic_delete?contactId='+row.contactId)
            .then((response) => {
              console.log(response.data)
              this.reload();
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    handleEdit(index,row) {
      this.contactId=row.contactId;
      this.dialogVisible = true;
      this.isStatus='update';
    },
    handleSearch(){

    },
    addGroupContact(){
      axios.post('http://localhost:8989/contact/add_group', this.groupForm)
          .then((response) => {
            console.log(response.data)
            this.reload();
            this.dialogVisible2 = false;
          });

    },
    updateGroupContact(){
      axios.post('http://localhost:8989/contact/update_group?groupId='+this.groupForm.groupId, this.groupForm)
          .then((response) => {
            console.log(response.data)
            this.reload();
            this.dialogVisible2 = false;
          });
    },
    deleteGroupContact(){
      this.$confirm('此操作将删除该分组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      axios.get('http://localhost:8989/contact/logic_delete_group?groupId='+this.groupForm.groupId)
          .then((response) => {
            console.log(response.data)
            this.reload();
            this.dialogVisible2 = false;
          });
      })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
    },
    getOneContact(contactId){
      axios.get('http://localhost:8989/contact/get_contact?contactId='+contactId)
          .then((response) => {
            console.log(response.data)
            this.contactForm.contactId=response.data.contactId;
            this.contactForm.contactName=response.data.contactName;
            this.contactForm.email=response.data.email;
            this.contactForm.remark=response.data.remark;
          })
      axios.get('http://localhost:8989/contact/group_name?contactId='+contactId)
          .then((response) => {
            console.log(response.data)
            this.contactForm.groupId=response.data.groupId;
          })

    },
    getOneGroup(groupId){
      axios.get('http://localhost:8989/contact/get_group?groupId='+groupId)
          .then((response) => {
            console.log(response.data)
            this.groupForm.groupId=response.data.groupId;
            this.groupForm.groupName=response.data.groupName;
          })
  }

  },
  watch:{
    isStatus(newValue){
      if(newValue==='update'){
        this.getOneContact(this.contactId);

      }else if(newValue==='add'){
        this.$refs.contactForm.resetFields();
      }else if(newValue==='addGroup'){
        this.$refs.groupForm.resetFields();
      }
    },
    'groupForm.groupId'(newVal, oldVal) {
      // 当groupId变化时，这里的代码会被执行
      console.log('groupId changed from', oldVal, 'to', newVal);
      // 你可以在这里添加你需要的逻辑，比如发送请求获取新数据等
      if(newVal!==0){
        this.getOneGroup(newVal);
      }
    }
  },
  mounted() {
  },
};
</script>
<style>
.contact-list{
  width: 100%;
  height: 100%;
  display: flex;
}
.contact-editor{
  width: 70%;

}
.contact-list-content{
  width: 30%;
}
.hide-header-table .el-table__header {
  display: none;
}
</style>